<script lang="ts" setup>

import {
    Edit,
    Delete, Plus
} from '@element-plus/icons-vue'
import { ref, reactive } from 'vue'
import { articleList, articleDelete, articleCategoryList, articleAdd, articleUpdate } from '@/api/artice.js'
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus'  // 添加这行引入
const tableData = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const background = ref(false)
const disabled = ref(false)
const total = ref()
// 如果查询传递的值，需要没有值传递的时候传递null 就将需要查询的数据单独声明
const categoryId = ref()
const state = ref()

const categoryList = ref([])
const article = reactive({
    categoryId: categoryId.value ? categoryId.value : null,
    state: state.value ? state.value : null,
    pageNum: pageNum.value,
    pageSize: pageSize.value
})
// 搜索
const onSubmit = () => {
    getArticleList();
}
// 重置
const reset = () => {
    article.categoryId = '';
    article.state = '';
    getArticleList();
}
const request = ref({
    pageNum: 1,
    pageSize: -1
})
// 获取文章分类
const getCategoryList = async () => {
    let res = await articleCategoryList(request.value);
    categoryList.value = res.data.items;
}
// 获取文章列表
const getArticleList = async () => {
    let res = await articleList(article);
    tableData.value = res.data.items;
    total.value = res.data.total;
    // 转换 key values值
    for (let i = 0; i < tableData.value.length; i++) {
        let artice = tableData.value[i];
        for (let j = 0; j < categoryList.value.length; j++) {
            if (artice.categoryId == categoryList.value[j].id) {
                artice.categoryName = categoryList.value[j].categoryName;
            }
        }
    }

}
// 删除数据
const showDelete = (row: { id: any }) => {

    ElMessageBox.confirm(
        '是否要删除此文章',
        '温馨提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            let res = await articleDelete(row.id);
            ElMessage({
                type: 'success',
                message: '删除成功',
            })
            getArticleList();
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}

// 分页
const handleSizeChange = (number: number) => {
    pageSize.value = number;
    getArticleList()
}
const handleCurrentChange = (number: number) => {
    pageNum.value = number;
    getArticleList()
}
//控制抽屉是否显示
const visibleDrawer = ref(false)
//添加表单数据模型
const articleModel = ref({
    id: '',
    title: '',
    categoryId: '',
    coverImg: '',
    content: '',
    state: ''
})

const title = ref();
// 发布文章
const showAdd = () => {
    visibleDrawer.value = true
    title.value = "添加文章"
}
// 富文本编辑器 
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'

// 导入token 
import { useTokenStore } from '@/stores/token'

const tokenStore = useTokenStore()

//上传成功的回调函数
const uploadSuccess = (result) => {
    articleModel.value.coverImg = result.data;
    console.log(result.data)
}

// 发布文件
const addActicle = async (clickState) => {
    articleModel.value.state = clickState;
    if (title.value == "添加文章") {
        let res = await articleAdd(articleModel.value)
        ElMessage.success(res.message ? res.message : "添加成功")
    }else if(title.value == "修改文章"){
        let res = await articleUpdate(articleModel.value)
        ElMessage.success(res.message ? res.message : "修改成功")
    }
    visibleDrawer.value = false;
    getArticleList();
}
// 编辑文章
const showUpdate = (row) => {
    visibleDrawer.value = true
    title.value = "修改文章"
    articleModel.value.id = row.id;
    articleModel.value.title = row.title;
    articleModel.value.categoryId = row.categoryId;
    articleModel.value.coverImg = row.coverImg;
    articleModel.value.state = row.state;
    articleModel.value.content = row.content;
}

// 网页加载的时候直接调用
getArticleList();
getCategoryList();
</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>文章管理</span>
                <div class="extra">
                    <el-button type="primary" @click="showAdd()">发布文章</el-button>
                </div>
            </div>
        </template>


        <div class="table-container">
            <el-form :inline="true" :model="article" class="demo-form-inline">
                <!-- <el-form-item label="文章标题">
                    <el-input v-model="article.title" placeholder="请输入文章标题" clearable />
                </el-form-item> -->
                <el-form-item label="文章分类">
                    <el-select v-model="article.categoryId" placeholder="请选择" clearable>
                        <el-option v-for="item in categoryList" :key="item.id" :label="item.categoryName"
                            :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="发布状态">
                    <el-select v-model="article.state" placeholder="请选择" clearable>
                        <el-option label="已发布" value="已发布" />
                        <el-option label="草稿" value="草稿" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit">搜索</el-button>
                    <el-button @click="reset">重置</el-button>
                </el-form-item>
            </el-form>

            <el-table :data="tableData" style="width: 100%" height="250">
                <el-table-column fixed label="序号" width="100" type="index" />
                <el-table-column prop="title" label="文章标题" align="center" />
                <el-table-column prop="categoryName" label="分类" align="center" />
                <el-table-column prop="createTime" label="发表时间" align="center" />
                <el-table-column prop="state" label="状态" align="center" />
                <el-table-column label="操作" align="center">
                    <template #default="{ row }">
                        <el-button :icon="Edit" circle plain type="primary" @click="showUpdate(row)"></el-button>
                        <el-button :icon="Delete" circle plain type="danger" @click="showDelete(row)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination-wrapper">
                <!-- hide-on-single-page="true" 当只有一页数据时隐藏分页条 -->
                <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 50, 100]" :disabled="disabled" :background="background"
                    layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" hide-on-single-page="true" />
            </div>
        </div>
        <!-- 抽屉 -->
        <el-drawer v-model="visibleDrawer" :title="title" direction="rtl" size="50%">
            <!-- 添加文章表单 -->
            <el-form :model="articleModel" label-width="100px">
                <el-form-item label="文章标题">
                    <el-input v-model="articleModel.title" placeholder="请输入标题"></el-input>
                </el-form-item>
                <el-form-item label="文章分类">
                    <el-select placeholder="请选择" v-model="articleModel.categoryId">
                        <el-option v-for="c in categoryList" :key="c.id" :label="c.categoryName" :value="c.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="文章封面">
                    <!-- 
                    auto-upload :设置是否自动上传
                    action:设置服务器接口路径
                    name:设置上传的文件字段名
                    headers：设置上传的请求头
                    on-success：设置上传成功的回调函数
                    -->
                    <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false"
                        action="/api/file/upload" name="file" :headers="{ 'Authorization': tokenStore.token }"
                        :on-success='uploadSuccess'>
                        <img v-if="articleModel.coverImg" :src="articleModel.coverImg" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="文章内容">
                    <div class="editor">
                        <quill-editor theme="snow" v-model:content="articleModel.content" contentType="html">
                        </quill-editor>
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="addActicle('已发布')">发布</el-button>
                    <el-button type="info" @click="addActicle('草稿')">草稿</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>
    </el-card>
</template>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .table-container {
        display: flex;
        flex-direction: column;
        height: 100%;
        position: relative;

        .pagination-wrapper {
            margin-top: auto;
            padding: 20px 0;
            display: flex;
            justify-content: end;
        }
    }
}

.demo-form-inline .el-select {
    --el-select-width: 220px;
}


/* // 设置输入框的宽度 
.demo-form-inline .el-input {
  --el-input-width: 220px;
} */
/* 抽屉样式 */
.avatar-uploader {
    :deep() {
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }

        .el-upload {
            border: 1px dashed var(--el-border-color);
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: var(--el-transition-duration-fast);
        }

        .el-upload:hover {
            border-color: var(--el-color-primary);
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            text-align: center;
        }
    }
}

.editor {
    width: 100%;

    :deep(.ql-editor) {
        min-height: 200px;
    }
}
</style>